const fs = require('fs');
const path = require('path');
const { parse } = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const vueCompiler = require('@vue/compiler-sfc');
const fg = require('fast-glob');

const APIS = ['wx', 'my', 'uni', 'Taro'];

function analyzeJS(source, filePath) {
  try {
    const ast = parse(source, {
      sourceType: 'module',
      plugins: [
        'jsx',
        'typescript',
        'classProperties',
        'decorators-legacy',
      ],
    });

    traverse(ast, {
      MemberExpression(path) {
        const { object, property, loc } = path.node;
        if (
          object &&
          property &&
          object.type === 'Identifier' &&
          APIS.includes(object.name)
        ) {
          const line = loc?.start?.line || '?';
          console.log(`[${filePath}:${line}] → ${object.name}.${property.name}`);
        }
      },
    });
  } catch (err) {
    console.error(`⚠️ Failed to parse ${filePath}:`, err.message);
  }
}

function parseVue(filePath) {
  const content = fs.readFileSync(filePath, 'utf-8');
  const { descriptor } = vueCompiler.parse(content);
  const scriptContent =
    descriptor.script?.content || descriptor.scriptSetup?.content || '';
  if (scriptContent) {
    analyzeJS(scriptContent, filePath);
  }
}

function main(root) {
  console.log('analyze', root);

  const files = fg.sync([root + '/**/*.{js,jsx,ts,tsx,vue}']);
  files.forEach((file) => {
    const ext = path.extname(file);
    if (ext === '.vue') {
      parseVue(file);
    } else {
      const source = fs.readFileSync(file, 'utf-8');
      analyzeJS(source, file);
    }
  });
}

if (!process.argv[2]) {
    console.error('Usage: node lib/index path/to/src');
} else {
    main(process.argv[2]);
}
